<template>
  <view style="height: 100vh;">
    <image src="../../static/share-bg.png" class="fixed-bg"></image>
    <view class="share-container">
      <uni-nav-bar left-icon="back" @clickLeft="gotoBack" color="#fff" status-bar="true" :border="false"
        background-color="transparent" left-width="20px">
        <view style="line-height: 44px;">
          <navigator url="/pages/index/index" open-type="switchTab">
            <uni-icons type="home-filled" color="#fff" size="22"></uni-icons>
          </navigator>
        </view>
      </uni-nav-bar>
    </view>
    <view class="share-panel-container">
      <canvas canvas-id="shareCanvas" type="2d" id="shareCanvas" class="share-canvas"
        :style="{height: canvasHeight+'px', width:canvasWidth+'px'}"></canvas>
    </view>
    <view class="qrcode-container">
      <uqrcode ref="uqrcode" canvas-id="qrcode" :value="qrcodurl" :options="{margin:5}" :hide="true"></uqrcode>
    </view>
    <view class="button-container flex">
      <button type="default" open-type="share">发给好友</button>
      <view style="text-align: center;" @click="downloadImage">
        <view>
          <uni-icons type="download-filled" size="20" color="#49c8bf"></uni-icons>
        </view>
        <text style="font-size: 28rpx;">下载图片</text>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    getUserPostcardList
  } from '@/apis/postcard.js'
  const dpr = uni.getSystemInfoSync().devicePixelRatio;
  export default {
    data() {
      return {
        canvasWidth: 350,
        canvasHeight: 350,
        qrCodeWidth: 100,
        gap: 20,
        canvas: null,
        qrcodurl: '',
      };
    },
    onLoad(option) {

      this.postcardId = option.postcardId;
      this.userId = option.userId;
      this.getCanvas()
      getUserPostcardList({
        id: this.postcardId
      }).then(res => {
        const cardInfo = res.rows[0];
        let cliperImg = 'https://' + (cardInfo.frontPostcardUrl || cardInfo.frontImgUrl || cardInfo.postcard
          .frontImgUrl)
        const image = uni.createOffscreenCanvas().createImage();
        image.src = cliperImg;
        this.friendName = cardInfo.sending
        this.sign = cardInfo.sign
        uni.showLoading({
          title: '正在加载'
        })
        this.qrcodurl =
          `https://app-whyt.xllibrary.com/detail/?userId= ${this.userId}&postcardId=${this.postcardId}`;
        this.$refs.uqrcode.make()
        try {
          this.generateQrCode(cliperImg)
        } catch (e) {
          this.$showtoast('系统出现问题,请重新加载')
        }
      })

    },
    onShareAppMessage() {
      return {
        title: `${this.friendName},我想对你说的话都在这里`,
        path: '/pages/detail/detail?postcardId=' + this.postcardId + "&userId=" + this.userId + '&replay=1'
      }
    },
    methods: {
      gotoBack() {
        uni.switchTab({
          url: '/pages/index/index'
        })
      },
      getCanvas() {
        const query = wx.createSelectorQuery();
        query.select('#shareCanvas').fields({
            node: true,
            size: true
          })
          .exec(res => {
            this.canvas = res[0].node;
          })
        query.select('.share-panel-container').fields({
          size: true
        }).exec(res => {
          this.maxWidth = res[1].width;
        })
      },
      generateQrCode(cliperImg) {

        this.$refs.uqrcode.toTempFilePath({
          success: res => {
            this.qrcodeFilePath = res.tempFilePath
            uni.hideLoading()
            this.drawCliperImage(cliperImg)
          }
        })

      },
      drawCliperImage(cliperImg) {
        const image = this.canvas.createImage();
        const {
          maxWidth,
          qrCodeWidth,
          gap,
          sign
        } = this;
        uni.getImageInfo({
          src: cliperImg,
          success: (res) => {
            image.src = res.path;
            image.onload = () => {
              this.canvasWidth = Math.min(maxWidth, image.width);
              const imageRenderHeight = (this.canvasWidth - 20) * image.height / image.width;
              this.canvasHeight = imageRenderHeight + qrCodeWidth + gap * 2;
              this.canvas.width = this.canvasWidth * dpr;
              this.canvas.height = this.canvasHeight * dpr
              this.imageWidth = image.width;
              this.imageHeight = image.height;

              this.ctx = this.canvas.getContext('2d')
              this.ctx.scale(dpr, dpr)
              this.ctx.fillStyle = '#FFFFFF';
              this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height)
              this.drawImage(image, 10, 10, this.canvasWidth - 20, imageRenderHeight)
              this.drawLogo()
              this.drawQrCode()
              this.drawTitleText(sign, 15)
              this.drawTitleText('寄来一张明信片', 40)
              this.drawTitleText('扫码听听Ta的声音~', 65, 13, '#535353')

            }
          },
          fail(e) {
            console.log(e)
          }
        })
      },
      drawImage(imgUrl, dx, dy, dWidth, dHeight) {
        this.ctx.drawImage(imgUrl, dx, dy, dWidth, dHeight);
      },
      drawLogo() {
        const image = this.canvas.createImage()
        image.src = '../../static/logo.png';
        image.onload = () => {
          const dHeight = 40;
          const dWidth = image.width * dHeight / image.height;
          const dx = this.canvasWidth - dWidth - 10;;
          const dy = 10;
          this.drawImage(image, dx, dy, dWidth, dHeight)
        }
      },
      drawQrCode() {
        const {
          ctx,
          imageHeight,
          imageWidth,
          gap,
          qrCodeWidth
        } = this
        const imageRenderHeight = this.canvasWidth * imageHeight / imageWidth;
        const dy = imageRenderHeight + gap;
        const dx = 20
        const image = this.canvas.createImage()
        image.src = this.qrcodeFilePath;
        image.onload = () => {
          this.drawImage(image, dx, dy, qrCodeWidth, qrCodeWidth)
        }
      },
      drawTitleText(content, ndy = 0, fontSize = 15, color = '#000000') {
        const {
          qrCodeWidth,
          imageHeight,
          gap,
          imageWidth,
          ctx
        } = this;
        const imageRenderHeight = this.canvasWidth * imageHeight / imageWidth;
        const dy = imageRenderHeight + gap + ndy;
        let dx = 20 + qrCodeWidth + gap;

        ctx.font = `${fontSize}px sans-serif`
        ctx.fillStyle = color
        const textWidth = ctx.measureText(content).width;
        if (dx + textWidth > this.canvasWidth - 30) {
          dx = this.canvasWidth - textWidth - 10
        }
        ctx.fillText(content, dx, dy)
      },
      downloadImage() {
        uni.canvasToTempFilePath({
          canvas: this.canvas,
          destWidth: this.canvasWidth * 3,
          destHeight: this.canvasHeight * 3,
          success(res) {
            uni.authorize({
              scope: 'scope.writePhotosAlbum',
              success() {
                uni.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: (r) => {
                    uni.showToast({
                      title: '文件保存成功',
                      icon: 'none'
                    })
                  },
                  fail: (e) => {
                    console.log(e)
                  }
                })
              }
            })

          },
          fail: (err) => {
            console.log(err)
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  .share-panel-container {
    padding: 20rpx;
  }

  .share-canvas {
    max-width: 100%;
    margin: 0 auto;
    margin-top: 100rpx;
    background-color: #fff;
  }

  .button-container button {
    margin: 0;
    font-size: 30rpx;
  }

  .button-container {
    margin: 20rpx;
    justify-content: space-around;
    align-items: center;
    position: relative;
    z-index: 1;
    font-size: 28rpx;
    color: #49c8bf;
  }
</style>